let app = getApp()
Component({ 
    properties: {
         pagetitle:String,
         parent:String
      },
      data:{
        list: [],
        editStatus:0,
        editindex:0,
        checkedId: 1,
        validate: {
            consigner: [ {
                rule:'\S+',
                message: "收件人名称不能为空"
            } ],
            phone: [{
                rule:'^1\d{10}$',
                message: "手机号格式不正确"
            } ],
            areaCode: [ {
              rule:'\S+',
              message: "请选择收货区域"
            } ],
            address: [ {
                rule:'\S+',
                message: "请填写收货详细地址"
            } ]
        },
        errorMsg: {
            message: "",
            name: "",
            index: -1
        },
        page_path: "pages/address/address"
      },
    lifetimes: {
        attached: function () {
          this.setData({
            globalColor:app.globalData.globalColor
          })
         this.get_data();
       }
      },
    methods: {
      get_data:function(){
        var that=this
        wx.request({
            url: app.globalData.siteroot,
            data: {
              do:'Member_userAddressList',
              user_id:wx.getStorageSync('user_id')
            },
            success: function(res) {
              that.setData({
                list:res.data.data
              })
            }
          })
      },
      edit:function(e){
        if(this.data.editStatus==1){
          wx.showToast({
            title: "请先完成正在编辑的地址",
            icon: "none"
          });
        }else{
          var index=e.currentTarget.dataset.key
          var list=this.data.list
          list[index].edit=true
          var edit_address=list[index]
          console.log(edit_address)
          this.setData({
            list:list,
            editindex:e.currentTarget.dataset.key,
            editStatus:1,
            edit_address:edit_address
          })
        }
       
      },
      confirmorder:function(e){
        console.log(this.data.parent)
        if(this.data.parent=='confirmorder'){
          var index=e.currentTarget.dataset.index
          var addr=this.data.list[index]
          var that=this
          wx.request({
            url: app.globalData.siteroot,
            data: {
              do:'Member_userAddress',
              user_id:wx.getStorageSync('user_id'),
              id:addr.id,
              consigner:addr.consigner,
              area:addr.area,
              phone:addr.phone,
              address:addr.address,
              zip_code:addr.zip_code,
              is_default:1
            },
            success: function(res) {
              that.get_data();
              wx.showToast({
                title: '更新成功',
                icon: 'none',
                duration: 1500
              })
              wx.navigateBack({
                delta: 1,
                success: function() {
                }
              })
            }
          })
        }
      },
      setdefault:function(e){
        if(this.data.editStatus==1){
          var index=e.currentTarget.dataset.index
          var list=this.data.list
          list[index].is_default=1;
          this.setData({
            list:list
          })
           this.save();
        }else{
          if(e.currentTarget.dataset.id==1){
            return false
          }
          var index=e.currentTarget.dataset.index
          var addr=this.data.list[index]
          var that=this
          wx.request({
            url: app.globalData.siteroot,
            data: {
              do:'Member_userAddress',
              user_id:wx.getStorageSync('user_id'),
              id:addr.id,
              consigner:addr.consigner,
              area:addr.area,
              phone:addr.phone,
              address:addr.address,
              zip_code:addr.zip_code,
              is_default:1
            },
            success: function(res) {
              that.get_data();
              wx.showToast({
                title: '更新成功',
                icon: 'none',
                duration: 1500
              })
            if(that.data.parent=='confirmorder'){
                wx.navigateBack({
                  delta: 1,
                  success: function() {
                  }
                })
              } 
            }
          })
        }
      
       
      },
      cancel:function(e){
      /*   var array=this.data.list
        var index=e.currentTarget.dataset.key
        var list=this.data.list
        list[index].edit=false
        array.splice(this.data.list.length-1, 1);
        this.setData({
          list:array,
          editStatus:0
        }) */
        this.setData({
          editStatus:0
        })
        this.get_data();
      },
      delete:function(e) {
        var id=e.currentTarget.dataset.id
        var index=e.currentTarget.dataset.key
        var is_default=e.currentTarget.dataset.is_default
        if(is_default==1)
        {
          wx.showToast({
            title: '默认地址无法删除',
            icon: 'none',
            duration: 1500
          })
        }else{
          var array=this.data.list
          var that=this
          wx.showModal({
            title: '提示',
            content: '确认将该收货地址删除？删除后无法恢复',
            showCancel: true,
            cancelText:"取消",
            confirmText:"确定",
            confirmColor: '#ff4040',
            success: function (res) {
              if (res.cancel) {
             } else{
              wx.request({
                url: app.globalData.siteroot,
                data: {
                  do:'Member_userAddressDel',
                  user_id:wx.getStorageSync('user_id'),
                  id:id
                },
                success: function(res) {
                  array.splice(index, 1);
                  that.setData({
                    list:array
                  })
                }
              })
              wx.showToast({
                title: '删除成功！',
                icon: 'none',
                duration: 1500
              })
             }
             },
             fail: function (res) { },
             complete: function (res) { }
        })
        }
        
      },
      errorMsg:function(){
        var errorMsg={
          message: "",
          name: "",
          index: -1
        }
        this.setData({errorMsg:errorMsg})
      },
      updete(name,val){
        this.errorMsg()
        var edit_address=this.data.edit_address
        if(typeof(val)!='undefined')
        {
          edit_address[name]=val
          this.setData({
            edit_address:edit_address
           })
        }
      },
      addresschange:function(e){
           this.updete('address',e.detail.value)
      },
      consignerchange:function(e){
          this.updete('consigner',e.detail.value)
      },
      phonechange:function(e){
        this.updete('phone',e.detail.value)
      },
      save:function(){
        if(this.data.editStatus)
        {
          this.switchEditStatus(this.data.list, "save", 1);
          /* this.setData({
            editStatus:0
          })
          this.get_data(); */
        }else{
          var s = {
            consigner:'',
            phone:'',
            areaCode:'',
            area: [undefined,undefined,undefined],
            address:'',
            edit: !0,
            postcode:'',
            checked: !1,
            is_default:0
        };
        var address= this.data.list;
        address.unshift(s),
        this.setData({
          list:address,
          edit_address:s,
          editindex:address.length-1,
          parent:'confirm_order_address'
        })
        this.switchEditStatus(address, "save", 0);
        }
      },
      switchEditStatus: function(tl, s, i) {
        var r = this;
        if ("save" !== s && "cancel" !== s){
          wx.showToast({
            title: "请先完成正在编辑的地址",
            icon: "none"
          });
          return false;
        }else if ("save" === s) {
          r.setData({
            editStatus:1
          })
            var validate=this.data.validate
            var list=tl
            for(var h = 0; h <list.length; h++){
              var t = {
                consigner:list[h].consigner,
                phone:list[h].phone,
                areaCode:list[h].areaCode,
                area:list[h].area,
                address:list[h].address,
                edit:list[h].edit,
                postcode:list[h].postcode,
                checked:list[h].checked,
                is_default:list[h].is_default,
            }
            for (var l in validate){
              for (var a = 0; a < validate[l].length; a++) {
                var mobile=t[l]
                var myreg ='';
                var message=validate[l][a].message;
                if(l=='consigner'||l=='address'||l=='areaCode')
                {
                  myreg=/\S+/
                }
                if(l=='phone')
                {
                  myreg=/^1\d{10}$/
                  if(mobile==''){
                    message='收件人手机号不能为空';
                  }else{
                    message=validate[l][a].message;
                  }
                }
              
                if (!myreg.test(mobile)) {
                  var errorMsg={
                    message:message,
                    name:l,
                    index:h
                  }
                  if(i==1){
                    r.setData({
                      errorMsg:errorMsg
                    })
                    wx.showToast({
                      title:message,
                      icon: "none"
                    });
                    return false;
                  }
                  return false
                }
              }
            }
            }
          
        }
        if(i==1)
        {
          var that=this
          var edit_address=that.data.edit_address
          var list=that.data.list
          list[this.data.editindex].edit=false
          if(typeof(edit_address.areaCode)=='undefined'){
            edit_address.areaCode=edit_address.area
          }
          if(typeof(edit_address.id)!='undefined'){
            wx.request({
              url: app.globalData.siteroot,
              data: {
                do:'Member_userAddress',
                id:typeof(edit_address.id)!=''?edit_address.id:'',
                user_id:wx.getStorageSync('user_id'),
                consigner:edit_address.consigner,
                area:edit_address.areaCode,
                phone:edit_address.phone,
                address:edit_address.address,
                zip_code:edit_address.areaCode,
                is_default:edit_address.is_default
              },
              success: function(res) {
                that.setData({
                  editStatus:0,
                  list:list
                })
                that.get_data();
                wx.showToast({
                  title: '保存成功',
                  icon: 'none',
                  duration: 1500
                })
              }
            })
          }else{
            wx.request({
              url: app.globalData.siteroot,
              data: {
                do:'Member_userAddress',
                user_id:wx.getStorageSync('user_id'),
                consigner:edit_address.consigner,
                area:edit_address.areaCode,
                phone:edit_address.phone,
                address:edit_address.address,
                zip_code:edit_address.areaCode,
                is_default:edit_address.is_default
              },
              success: function(res) {
                that.setData({
                  editStatus:0,
                  list:list
                })
                that.get_data();
                wx.showToast({
                  title: '保存成功',
                  icon: 'none',
                  duration: 1500
                })
              }
            })
          }
          
        }
      },
      area:function(e) {
        var edit_address=this.data.edit_address
        edit_address['areaCode']=e.detail.area
        edit_address['region']=[e.detail.pickVal[0],e.detail.pickVal[1],e.detail.pickVal[2]]
        this.setData({
          edit_address:edit_address
        })
      },
      goToWechatAddress:function(){
        var that=this
        if(this.data.editStatus)
        {
          wx.showToast({
            title: "请先完成正在编辑的地址",
            icon: "none"
          });
        }else{
          wx.authorize({
            scope: "scope.address",
            success: function() {
                wx.chooseAddress({
                    success: function(e) {
                      var is_default=0;
                       var len=that.data.list.length
                       if(len==0){is_default=1}
                        if (e.userName) {
                            var s = {
                                consigner: e.userName,
                                phone: e.telNumber,
                                areaCode:e.nationalCode,
                                area: [ e.provinceName, e.cityName, e.countyName],
                                address: e.detailInfo,
                                edit: !0,
                                postcode: e.postalCode,
                                checked: !1,
                                is_default:is_default
                            };
                            var address= that.data.list;
                            address.unshift(s),
                            that.setData({
                              list:address,
                              edit_address:s,
                              editindex:address.length-1,
                              parent:'confirm_order_address'
                            })
                            var edit_address=s
                            wx.request({
                              url: app.globalData.siteroot,
                              data: {
                                do:'Member_userAddress',
                                user_id:wx.getStorageSync('user_id'),
                                consigner:edit_address.consigner,
                                area:edit_address.areaCode,
                                phone:edit_address.phone,
                                address:edit_address.address,
                                zip_code:edit_address.areaCode,
                                is_default:edit_address.is_default
                              },
                              success: function(res) {
                                that.setData({
                                  editStatus:0,
                                  list:address
                                })
                                that.get_data();
                                wx.showToast({
                                  title: '添加成功',
                                  icon: 'none',
                                  duration: 1500
                                })
                              }
                            })
                        }
                    },
                    fail: function(e) {
                        console.log("失败"), console.log(e);
                    }
                });
            }
        });
        }
       
      }
    }
});
